// timer.js
let globalTimer = null;
let appInstance = null;
let globalEvent = null;
let hhwUHFController = null;
let page_state = {
  dataList: [],
  epcList: [],
  tempList: [],
  tagsAmount: 0,
  btn1Info: "开始盘点",
  btn2Disabled: false,
  btn3Disabled: false,
  cbDisabled: false
};
let offset= 50;
let highestRssi=-100;
let highestRssiTag=null;
import {sendPosition} from '@/api/admin.js'
// 扫描逻辑
function handleScan() {
	var fdata =  hexString2Bytes("484a")
	// 盘点过滤数据区域，1 => EPC区，2 => TID区，3 => USER区
	var fbank = 1
	// 盘点过滤起始地址，指标签数据区域的起始地址，比如：3，代表从标签数据区的第3*2个字节开始匹配数据；EPC区需要从2开始，详情参考“标签读写注意事项”中关于EPC区数据结构的描述
	var fstartaddr = 2
	// 显示匹配的标签，或不匹配的标签。true => 显示匹配的标签，false => 显示不匹配的标签
	var matching = true
	// 设置盘点过滤条件
	
	hhwUHFController.setInventoryFilter(fdata, fbank, fstartaddr, matching, result => {
		console.log("inventory inventory", "setInventoryFilter " + result)
	})
	hhwUHFController.startInventory(30, 0, false, 1000, true, result => {
		console.log("inventory inventory", "startInventory " + result)
		send2Position()
	})
	


}
//
function init(){
	
    hhwUHFController = getApp().globalData.hhwUHFController;
	
	globalEvent = getApp().globalData.globalEvent;
    
	globalEvent.addEventListener('uhf_tag_event', async (e)=> {
		console.log(e.tag_info_list)
		
		var result = e.tag_info_list
		if (result == null) {
			// 接收到停止盘点的回调消息
			var event = e.inventory_event
			if (event == "stopInventory") {
				// uni.showToast({
				// 	title: "停止盘点",
				// 	icon: "none"
				// })
				page_state.btn2Disabled = false
				page_state.btn3Disabled = false
				page_state.cbDisabled = false
				page_state.btn1Info = "开始盘点"
	
			}
			return
		}
		// 接收盘点到的标签信息
		for (var i = 0; i < result.length; i++) {
		  var id = i;
		  var epc = bytes2HexString(result[i].EpcId);
		  var rssi = result[i].RSSI;
		  // 获取标签tid，配合startEpcTidInventory使用
		  // var EmbededData = bytes2HexString(result[i].EmbededData)
		  // console.log("tagEpcTidInventoryByTimer", "epc:" + epc ,  "Tid: " + EmbededData)
		  epc = hexToText(epc)
		  var tag = {
		    id: id,
		    epc: epc,
		    count: 1,
		    rssi: rssi,
		  };
		
		// 过滤掉 epc 不以 "AA" 开头的项
		// console.log("epc",epc)
		if (!/^HJ/.test(epc)) {
		  continue; // 如果 epc 不以 "AA" 开头，则跳过此项
		}
		// console.log("result",rssi)
			  // 更新最高 RSSI 值及对应的标签信息
			  if (rssi > highestRssi) {
				highestRssi = rssi;
				highestRssiTag = tag;
			  }
		}
		console.log("highestRssiTag",highestRssiTag)

		
		
	})

}

function bytes2HexString(byteArray) {
  return Array.from(byteArray, function(byte) {
    return ('0' + (byte & 0xFF).toString(16)).slice(-2);
  }).join('');
}

function send2Position(){
		if(highestRssiTag!=null){
			sendPosition(highestRssiTag).then(res=>{
				console.log(res);
			
			})
			highestRssiTag=null
			highestRssi=-100
		}
}

export function startGlobalTimer(interval = 10000) {
  if (globalTimer) {
    clearInterval(globalTimer);
  }
  init();
  globalTimer = setInterval(handleScan, interval);
}

 function hexToText(hexString) {
	  let text = '';
	  for (let i = 0; i < hexString.length; i += 2) {
		  let hex = hexString.substring(i, i + 2);
		  text += String.fromCharCode(parseInt(hex, 16));
	  }
	  return text;
}
	  
function hexString2Bytes(str) {
		var pos = 0
		var len = str.length
		if (len % 2 != 0) {
			return null
		}
		len /= 2
		var hexA = new Array()
		for (var i = 0; i < len; i++) {
			var s = str.substr(pos, 2)
			var v = parseInt(s, 16)
			hexA.push(v)
			pos += 2
		}
		return hexA
	}


export function stopGlobalTimer() {
  if (globalTimer) {
    clearInterval(globalTimer);
    globalTimer = null;
  }
}
